package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"lottery/comm"
	"lottery/models"
	"lottery/services"
	"net/http"
	"strconv"
)

type IndexController struct {
	ServiceUser    services.UserService
	ServiceGift    services.GiftService
	ServiceCode    services.CodeService
	ServiceResult  services.ResultService
	ServiceUserday services.UserdayService
	ServiceBlackip services.BlackipService
}

// http://localhost:8080/ : 首页
func (idx *IndexController) Get(c *gin.Context) {
	//var s = "welcome to Go抽奖系统,<a href='/public/index.html'>开始抽奖</a>"
	// 模板渲染数据
	c.HTML(http.StatusOK, "cnt/index", nil)
	//c.Data(http.StatusOK, "text/html", []byte(s))
}

// localhost:8080/gifts 获取所有的礼品信息： 返回json格式数据
func (idx *IndexController) GetGifts(c *gin.Context) {
	// datalist 奖品列表， total 商品总数
	datalist := idx.ServiceGift.GetAll(true)
	//列表中的  PrizeData string 这个字段要进行一下转换才能输出给模板（时间戳转 时间）
	total := len(datalist)
	for i, gift := range datalist {
		prizeData := make([][2]int, 0)
		// 将string 类型的原数据，转换为 []byte 切片。 再进行 反序列化，存入prizeData
		err := json.Unmarshal([]byte(gift.PrizeData), &prizeData)
		if err != nil || len(prizeData) < 1 {
			// 没数据， 传递默认值进去为 "[]"
			datalist[i].PrizeData = "[]"
		} else {
			// 对 prizeData 再做一次处理, 转换
			newpd := make([]string, len(prizeData))
			for index, pd := range prizeData {
				ct := comm.FormatFromUnixTime(int64(pd[0])) // 时间
				newpd[index] = fmt.Sprintf("[%s]: %d",
					ct, pd[1]) // 转字符串处理
			}
			// 进行序列化
			str, err := json.Marshal(newpd)
			if err == nil && len(str) > 0 {
				datalist[i].PrizeData = string(str)
			} else {
				// 否则还使用默认值进去
				datalist[i].PrizeData = "[]"
			}
		}
		// （后期新增） 获取当前的奖品池数据
		// 将title 字段进行更改，显示当前商品的奖品池中的数量
		//num := utils.GetGiftPoolNum(gift.Id)
		//datalist[i].Title = fmt.Sprintf("【%d】%s", num, datalist[i].Title)
	}
	c.HTML(http.StatusOK, "cnt/ing", gin.H{
		"Title":    "奖品",
		"Channel":  "gift",
		"Datalist": datalist,
		"Total":    total,
	})
}

// localhost:8080/newprize 最新获奖列表
func (idx *IndexController) GetNewPrize(c *gin.Context) {
	// 获取参数
	giftId, _ := strconv.Atoi(c.DefaultQuery("gift_id", "0"))
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	uid, _ := strconv.Atoi(c.DefaultQuery("uid", "0"))
	size := 10 // 默认页面大小为 10

	user := comm.GetLoginUser(c.Request)
	uid = user.Uid
	//uid = 1
	// 数据列表构建, 总数
	var (
		total    int
		pagePrev string // 上下页码
		pageNext string
		datalist []models.LtResult
	)
	// 通过奖品id, uid 来进行搜索,  或者查找全部的数据
	if giftId > 0 {
		datalist = idx.ServiceResult.SearchByGift(giftId, page, size)
	} else if uid > 0 {
		datalist = idx.ServiceResult.SearchByUser(uid, page, size)
	} else {
		datalist = idx.ServiceResult.GetAll(page, size)
	}
	total = (page-1)*size + len(datalist)
	if len(datalist) >= size {
		// 后面还有页数
		if giftId > 0 {
			total = int(idx.ServiceResult.CountByGift(giftId))
			fmt.Println("####### ", total)
		} else if uid > 0 {
			total = int(idx.ServiceResult.CountByUser(uid))
		} else {
			total = int(idx.ServiceResult.CountAll())
		}
		pageNext = fmt.Sprintf("%d", page+1)
	}
	if page > 1 {
		pagePrev = fmt.Sprintf("%d", page-1)
	}

	c.HTML(http.StatusOK, "cnt/rewin", gin.H{
		"Title":    "管理后台",
		"Channel":  "result",
		"GiftId":   giftId,
		"Uid":      uid,
		"Datalist": datalist,
		"Total":    total,
		"PagePrev": pagePrev,
		"PageNext": pageNext,
	})
}

func (idx *IndexController) NewPrize(c *gin.Context) {
	// 获取参数
	giftId, _ := strconv.Atoi(c.DefaultQuery("gift_id", "0"))
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	uid, _ := strconv.Atoi(c.DefaultQuery("uid", "0"))
	size := 10 // 默认页面大小为 10

	//user := comm.GetLoginUser(c.Request)
	//uid = user.Uid
	//uid = 1
	// 数据列表构建, 总数
	var (
		total    int
		pagePrev string // 上下页码
		pageNext string
		datalist []models.LtResult
	)
	// 通过奖品id, uid 来进行搜索,  或者查找全部的数据
	if giftId > 0 {
		datalist = idx.ServiceResult.SearchByGift(giftId, page, size)
	} else if uid > 0 {
		datalist = idx.ServiceResult.SearchByUser(uid, page, size)
	} else {
		datalist = idx.ServiceResult.GetAll(page, size)
	}
	total = (page-1)*size + len(datalist)
	if len(datalist) >= size {
		// 后面还有页数
		if giftId > 0 {
			total = int(idx.ServiceResult.CountByGift(giftId))
			fmt.Println("####### ", total)
		} else if uid > 0 {
			total = int(idx.ServiceResult.CountByUser(uid))
		} else {
			total = int(idx.ServiceResult.CountAll())
		}
		pageNext = fmt.Sprintf("%d", page+1)
	}
	if page > 1 {
		pagePrev = fmt.Sprintf("%d", page-1)
	}

	total = len(datalist)
	if len(datalist) > 10 {
		total = 10
		datalist = datalist[:10]
	}

	c.HTML(http.StatusOK, "cnt/rewin", gin.H{
		"Title":    "管理后台",
		"Channel":  "result",
		"GiftId":   giftId,
		"Uid":      uid,
		"Datalist": datalist,
		"Total":    total,
		"PagePrev": pagePrev,
		"PageNext": pageNext,
	})
}

// 实现登录退出的一些接口
// 登录：
func (idx *IndexController) GetLogin(c *gin.Context) {
	// 生成uid
	uid := comm.Random(100000)
	// 创建用户对象
	loginUser := models.ObjLoginuser{
		Uid:      uid,
		Username: fmt.Sprintf("admin-%d", uid),
		Now:      comm.NowUnix(),
		Ip:       comm.ClientIp(c.Request),
	}
	// 设置cookie登录， 安置cookie
	comm.SetLoginuser(c.Writer, &loginUser)
	// 跳转页面到 /public/index.html
	c.Redirect(http.StatusFound, "/public/index.html?form=login")
}

// 退出：
func (idx *IndexController) GetLogout(c *gin.Context) {
	// 删除cookie, 退出登录
	comm.SetLoginuser(c.Writer, nil) // nil 表示删除当前登录cookie
	// 跳转到首页
	c.Redirect(http.StatusFound, "/public/index.html?form=logout")
}
